package com.totoro.tyrank.utils;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.NBTKeyConst;
import com.totoro.tyrank.constants.PatternConst;
import com.totoro.tyrank.constants.StaticSystemVarConst;
import com.totoro.tyrank.constants.TagConst;
import com.totoro.tyrank.data.ItemDisplayData;
import com.totoro.tyrank.data.PlayerData;
import com.totoro.tyrank.data.RankingData;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

public class ItemStackUtil {

    /**
     * 获取所有/历史排行榜数据内容
     * @param rankingData
     * @return
     */
    public static ItemStack getRankItemStackByRankingData(Player player, RankingData rankingData) {
        // 获取该排行榜所有人集合
        Map<String, LinkedList<PlayerData>> playersDataMap = TyRank.getPlayerDataManager().getPlayersDataMap();
        LinkedList<PlayerData> playerDataList = playersDataMap.get(rankingData.getId());
        // 先获取ItemStack，排行榜ID使用NBT存储
        ItemDisplayData itemDisplay = rankingData.getItemDisplay();
        ItemStack rankItemStack = ItemStackUtil.loadItem(itemDisplay.getId(), itemDisplay.getData(), 1);
        // 先设置name
        String status = DateUtil.isCurrentTimeAfter(rankingData.getEndTime()) ?
                TyRank.getLanguageManager().getLanguageData().getGui().getRankItemHasEndedStatus():
                TyRank.getLanguageManager().getLanguageData().getGui().getRankItemInProgressStatus();
        ItemMeta rankItemStackMeta = rankItemStack.getItemMeta();
        rankItemStackMeta.setDisplayName(itemDisplay.getName().replaceAll(TagConst.STATUS_TAG, status));
        // 设置Lore，设置规则如下：
        // 首先循环itemDisplay的Lore，将其中的<top1>等等替换为该榜名次对应玩家名
        // <other>要第二次循环
        int otherCounter = 0;
        List<String> rankFinalLore = new ArrayList<>();
        List<String> itemDisplayLore = itemDisplay.getLore();
        // 判断是否闭榜
        int statusLoreIndexOf = itemDisplayLore.indexOf(TagConst.STATUS_LORE_TAG);
        if(DateUtil.isCurrentTimeAfter(rankingData.getEndTime())) {
            if(statusLoreIndexOf != -1) {
                itemDisplayLore.remove(statusLoreIndexOf);
                itemDisplayLore.addAll(statusLoreIndexOf, TyRank.getLanguageManager().getLanguageData().getGui().getRankItemHasEndedLore());
            }
        } else {
            if(statusLoreIndexOf != -1) {
                itemDisplayLore.remove(statusLoreIndexOf);
                itemDisplayLore.addAll(statusLoreIndexOf, TyRank.getLanguageManager().getLanguageData().getGui().getRankItemInProgressLore());
            }
        }
        for (String loreLine : itemDisplayLore) {
            Matcher topTagMatcher = PatternConst.TOP_TAG_PATTERN.matcher(loreLine);
            // 更换endTime
            loreLine = loreLine.replaceAll(TagConst.END_TIME_TAG, rankingData.getEndTime().format(StaticSystemVarConst.DATE_FORMATTER));
            while (topTagMatcher.find()) {
                // 提取完整的<top>标签
                String topTag = topTagMatcher.group();
                // 提取数字
                String topGroup = topTagMatcher.group(1);
                int top = Integer.parseInt(topGroup);
                // 根据top和当前榜ID获取玩家并转换玩家名
                PlayerData currentTopPlayerData = TyRank.getPlayerDataManager().getPlayerDataByRankIdAndRanking(rankingData.getId(), top);
                String playerName = TyRank.getLanguageManager().getLanguageData().getGui().getTopNotAtTheMoment();
                if (null != currentTopPlayerData) {
                    otherCounter++;
                    playerName = TyRank.getPlayerDataManager().getPlayerName(currentTopPlayerData.getPlayerIdentity());
                }
                loreLine = loreLine.replaceAll(topTag, playerName);
            }
            // 解析<ranking> 当前玩家的排名
            PlayerData playerData = TyRank.getPlayerDataManager().getPlayerDataByRankId(player, rankingData.getId());
            String myRanking = "暂无";
            if(null != playerData) {
                myRanking = playerData.getRanking().toString();
            }
            loreLine = loreLine.replace(TagConst.RANKING_TAG, myRanking);
            Matcher topTagValueMatcher = PatternConst.TOP_VALUE_TAG_PATTERN.matcher(loreLine);
            while (topTagValueMatcher.find()) {
                // 提取完整的<topValue>标签
                String topValueTag = topTagValueMatcher.group();
                // 提取数字
                String topGroup = topTagValueMatcher.group(1);
                int top = Integer.parseInt(topGroup);
                PlayerData currentTopPlayerData = TyRank.getPlayerDataManager().getPlayerDataByRankIdAndRanking(rankingData.getId(), top);
                loreLine = loreLine.replaceAll(topValueTag, currentTopPlayerData.getCurrentValue());
            }
            rankFinalLore.add(loreLine);
        }
        // 替换<other>标签
        int finalOtherCounter = otherCounter;
        rankFinalLore = rankFinalLore.stream().map(s -> {
            if(s.contains(TagConst.OTHER_TAG)) {
                return s.replaceAll(TagConst.OTHER_TAG,  String.valueOf((playerDataList.size() - finalOtherCounter)));
            }
            return s;
        }).collect(Collectors.toList());
        // 再设置lore
        rankItemStackMeta.setLore(rankFinalLore);
        rankItemStack.setItemMeta(rankItemStackMeta);
        // 添加NBT
        return NBTUtil.addNBT(rankItemStack, NBTKeyConst.RANK_ID, rankingData.getId());
    }

    /**
     * 根据Id和Data获取ItemsTack
     * @param id
     * @param data
     * @param amount
     * @return 对应的ItemStack，若无效则返回null
     */
    public static ItemStack loadItem(int id, int data, int amount) {
        if (id == -1) {
            return StaticSystemVarConst.EMPTY_ITEM_STACK;
        }

        try {
            // 1.12.2支持两种ID格式：数字ID和材料名（如"IRON_SWORD"）
            Material material;
            try {
                // 尝试解析为数字ID（如267对应铁剑）
                material = Material.getMaterial(id);
            } catch (NumberFormatException e) {
                // 尝试解析为材料名（如"IRON_SWORD"）
                material = Material.valueOf(String.valueOf(id));
            }

            if (material == null) {
                Bukkit.getLogger().warning("无效的物品ID: " + id);
                return StaticSystemVarConst.EMPTY_ITEM_STACK;
            }

            // 创建ItemStack并设置data（损伤值/子类型）
            ItemStack item = new ItemStack(material, amount);
            item.setDurability((short) data); // 1.12.2用setDurability设置data值

            return item;
        } catch (IllegalArgumentException e) {
            Bukkit.getLogger().warning("创建物品失败: " + e.getMessage());
            return StaticSystemVarConst.EMPTY_ITEM_STACK;
        }
    }

    /**
     * ItemStack是否不为空
     * @param itemStack
     * @return
     */
    public static Boolean isNotBlank(ItemStack itemStack) {
        return ! isBlank(itemStack);
    }

    /**
     * ItemStack是否为空
     * @param itemStack
     * @return
     */
    public static Boolean isBlank(ItemStack itemStack) {
        return null == itemStack || itemStack.getType() == Material.AIR;
    }

    /**
     * 获取TyRankGUI格挡板
     * @return
     */
    public static ItemStack getGridPlateItem() {
        ItemStack gridPlateItem = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short)15);
        ItemMeta gridPlateItemMeta = gridPlateItem.getItemMeta();
        gridPlateItemMeta.setDisplayName(ColorUtil.color(" "));
        gridPlateItem.setItemMeta(gridPlateItemMeta);
        return gridPlateItem;
    }

}
